# -*- coding: utf-8 -*-
# @file   : HboUpdate.py
# @author : songxulin
# @date   : 2021:08:20 14:00:00
# @version: 1.0
# @desc   : python windows监控
import datetime
import locale
import os
import subprocess
import sys
import urllib.request

import uvicorn
from fastapi import FastAPI
from fastapi.exception_handlers import (
    http_exception_handler
)
from pydantic import BaseModel

from hboMonitor import ComputerInfo

app = FastAPI()


# 创建数据模型
class Item(BaseModel):
    name: str = None
    batch: str = None
    ext: str = None


class Data:
    code: int = None
    data: object = None
    message: str = None

    def __init__(self, code, data, messge):
        self.data = data
        self.code = code
        self.message = messge


@app.exception_handler(Exception)
async def custom_http_exception_handler(request, exc):
    print(f"OMG! An HTTP error!: {repr(exc)}")
    return await http_exception_handler(request, exc)


@app.get('/test/a={a}/b={b}')
def calculate(a: int = None, b: int = None):
    return a + b


@app.get('/hboMonitor/computerInfo')
def computer_info():
    """ 获取机器信息"""
    return Data(code=10000, messge="ok", data=ComputerInfo.computer_info())


@app.post('/hboMonitor/reboot')
def reboot():
    # 10秒后关机
    os.system("shutdown -r -t  10 ")
    return Data(code=10000, messge="ok", data={})


@app.post('/hboMonitor/exit')
def exit_exe():
    os.system("taskkill /f /t /im HboMonitor.exe")
    return Data(code=10000, messge="ok", data={})


@app.post('/hboMonitor/kill/name={name}')
def kill_exe(name: str = None):
    os.system("taskkill /f /t /im %s" % name)
    return Data(code=10000, messge="ok", data={})


@app.post('/hboMonitor/batch')
def batch_shell(item: Item):
    """shell执行"""
    r = {}
    try:
        r = subprocess.Popen(item.batch, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE).stdout.read()
        if sys.getdefaultencoding() != locale.getpreferredencoding():
            r = r.decode(locale.getpreferredencoding())
    except Exception as e:
        write_log(e.__doc__)
    return Data(code=10000, messge="ok", data=r)


def get_data_by_url(url):
    header = {
        'User-Agent': 'Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
    }  # 头部信息
    request = urllib.request.Request(url=url, headers=header)  # 请求处理
    b64_text = urllib.request.urlopen(request).read()  # 读取结果
    return b64_text


def write_log(text):
    f = open('c:/HboSoft/HboMonitor.log', mode='a', encoding='utf-8')
    f.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S' + "\t" + text + "\n"))
    f.close()


if __name__ == '__main__':
    process_list = []
    try:
        process_list = ComputerInfo.get_process_list()
        if 'HboMonitor.exe' in process_list and process_list.count('HboMonitor.exe') > 2:
            write_log("程序已经在运行")
        else:
            write_log("启动")
            uvicorn.run(app=app, host="0.0.0.0", port=80, workers=1)
    except Exception as e:
        write_log(e.__doc__)

